package com.jiuyin.dianjing.ui.fragment.main;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.MessageModel;
import com.jiuyin.dianjing.ui.activity.main.MainActivity;
import com.jiuyin.dianjing.ui.fragment.base.BaseFragment;
import com.jiuyin.dianjing.util.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import jiguang.ui.view.DropDownListView;
import jiguang.util.SharePreferenceManager;

import static jiguang.adapter.ChattingListAdapter.PAGE_MESSAGE_COUNT;

/**
 * 消息详情
 */
public class FragmentFour extends BaseFragment {
    @BindView(R.id.lv_chat)
    DropDownListView lvChat;

    @BindView(R.id.tv_title)
    public TextView mTitle;

    public static final String USER_NAME = "userName";

    private Conversation mConv;
    private String mUserName;
    private SystemMsgAdapter mSystemMsgAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_four;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        mUserName = bundle.getString(USER_NAME);
        mConv = JMessageClient.getSingleConversation(mUserName);
        if (mConv == null) {
            mConv = Conversation.createSingleConversation(mUserName);
        }
        if (null != mConv) {
            setUnReadMsg(mConv.getUnReadMsgCnt());
            List<Message> newest = mConv.getMessagesFromNewest(0, PAGE_MESSAGE_COUNT);
            if (null != newest) {
                int size = newest.size();
                if (0 != size) {
                    List<MessageModel> messageModels = new ArrayList<>(size);
                    for (Message message : newest) {
                        MessageModel messageModel = new MessageModel();
                        String msg = message.getContent().toJson();
                        LogUtil.log(" content1 = " + msg);
                        try {
                            JSONObject jsonObject = new JSONObject(msg);
                            String text = jsonObject.getString("text");
                            JSONObject textJson = new JSONObject(text);
                            String logo = textJson.getString("logo");
                            String time = textJson.getString("time");
                            String title = textJson.getString("title");
                            String content = textJson.getString("content");
                            messageModel.content = content;
                            messageModel.create_time = time;
                            messageModel.logo = logo;
                            messageModel.title = title;
                            messageModels.add(messageModel);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    reverse(messageModels);
                    mSystemMsgAdapter = new SystemMsgAdapter(messageModels, R.layout.item_message);
                    lvChat.setAdapter(mSystemMsgAdapter);
                    lvChat.setOnDropDownListener(() -> getOldMsg());
                    lvChat.setSelection(mSystemMsgAdapter.getCount());
                }
            }
        }
    }

    @Override
    protected void initView() {
        mTitle.setText(R.string.system_message);
        showReturnButton();
    }

    @Override
    public void fetchData() {
    }

    /**
     * 获取之前的系统消息
     */
    private void getOldMsg() {
        if (mConv != null) {
            List<Message> msgList = mConv.getMessagesFromNewest(mSystemMsgAdapter.getCount(), PAGE_MESSAGE_COUNT);
            lvChat.onDropDownComplete();
            if (msgList != null) {
                int size = msgList.size();
                if (0 != size) {
                    List<MessageModel> messageModels = new ArrayList<>(size);
                    for (Message message : msgList) {
                        MessageModel messageModel = new MessageModel();
                        String msg = message.getContent().toJson();
                        LogUtil.log(" content1 = " + msg);
                        try {
                            JSONObject jsonObject = new JSONObject(msg);
                            String text = jsonObject.getString("text");
                            JSONObject textJson = new JSONObject(text);
                            String logo = textJson.getString("logo");
                            String time = textJson.getString("time");
                            String title = textJson.getString("title");
                            String content = textJson.getString("content");
                            messageModel.content = content;
                            messageModel.create_time = time;
                            messageModel.logo = logo;
                            messageModel.title = title;
                            messageModels.add(messageModel);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    mSystemMsgAdapter.insert(messageModels);
                }
            }
        }

    }

    //进入页面，减去未读消息
    private void setUnReadMsg(int msg) {
        SharePreferenceManager.setUnReadMsgNum(SharePreferenceManager.getUnReadMsgNum() - msg);
        EventBus.getDefault().post(new RefreshEvent(MainActivity.class.getSimpleName()));
    }

    private static class SystemMsgAdapter extends BaseRecyclerAdapter<MessageModel> {

        public SystemMsgAdapter(Collection<MessageModel> list, int layoutId) {
            super(list, layoutId);
        }

        @Override
        protected void onBindViewHolder(SmartViewHolder holder, MessageModel model, int position) {
            holder.text(R.id.tv_system_title, model.title);
            holder.text(R.id.tv_system_notice_time, model.create_time);
            holder.text(R.id.tv_system_notice, model.content);
            ImageView imageView = holder.itemView.findViewById(R.id.iv_header);
            Glide.with(HelperApplication.getContext())
                    .load(model.logo)
                    .into(imageView);
        }
    }

    private void reverse(List<MessageModel> list) {
        if (list.size() > 0) {
            Collections.reverse(list);
        }
    }
}
